package org.rahar.masdar;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MasdarChecker extends Activity {
    private Button loginButton;
    String username;
    String password;
    private HttpContext httpContext = new BasicHttpContext();
    private HttpClient httpclient = new DefaultHttpClient();
    private Pattern pat = Pattern.compile("Application Status :[A-z 0-9^]*");
    private Handler handler;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.main);
        this.loginButton = (Button) this.findViewById(R.id.login);
        readData();
        handler = new Handler() {
            public void handleMessage(Message msg) {
                updateResult(msg.getData().getString("msg"));
            }
        };

        this.loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });

    }

    private void readData() {
        try {
            DataInputStream reader = new DataInputStream(openFileInput("masdardata.txt"));
            String data = reader.readUTF();

            ((EditText) this.findViewById(R.id.username)).setText(data.substring(0, data.indexOf("|")));
            ((EditText) this.findViewById(R.id.password)).setText(data.substring(data.indexOf("|")+1));
            reader.close();
        }
        catch (Exception ex) {

        }
    }

    private void writeData() {
       try {
           DataOutputStream dataOut = new DataOutputStream(openFileOutput("masdardata.txt",MODE_PRIVATE));
           dataOut.writeUTF(username+"|"+password);
           dataOut.close();
        }
        catch (Exception ex) {

        }
    }

    private void login() {
        ((TextView) this.findViewById(R.id.resultfield)).setText("Please wait, getting data");
        username = ((EditText) this.findViewById(R.id.username)).getText().toString();
        password = ((EditText) this.findViewById(R.id.password)).getText().toString();
        Log.i("MASDAR", username + "  " + password);
        new Thread() {
            @Override
            public void run() {
                postData();
            }
        }.start();
        writeData();

    }

    public void postData() {
        // Create a new HttpClient and Post Header
        HttpPost httppost = new HttpPost("http://apps.masdar.ac.ae/masdar/chk_status.php");
        HttpGet httpget = new HttpGet("http://apps.masdar.ac.ae/masdar/st_index.php");

        try {
            httpclient.execute(httpget, httpContext);
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("email", username));
            nameValuePairs.add(new BasicNameValuePair("pwd", password));
            nameValuePairs.add(new BasicNameValuePair("submit", "Login"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost, httpContext);
            Log.i("MASDAR", "STATUS: " + response.getStatusLine().getStatusCode());
            if (!parseData(response)) {
                getMainResultPage();
            }
            // }
        } catch (IOException e) {
            handler.sendMessage(createMsg("Error: "+e));
        }
    }

    public void getMainResultPage() {
        HttpGet httpGet = new HttpGet("http://apps.masdar.ac.ae/masdar/st_index.php");

        try {
            HttpResponse response = httpclient.execute(httpGet, httpContext);
            if (!parseData(response)) {
                handler.sendMessage(createMsg("Error: Wrong username or password :("));
            }

        } catch (IOException e) {
            handler.sendMessage(createMsg("Error: "+e));
        }
    }

    private void print(HttpResponse response) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String data;
            while ((data = reader.readLine()) != null) {
                System.out.println(data);
            }
        } catch (IOException e) {
            handler.sendMessage(createMsg("Error: "+e));
        }
    }

    private boolean parseData(HttpResponse response) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String data;
            while ((data = reader.readLine()) != null) {
                //if(data.contains("<strong>Application Status :[A-z 0-9^<]*</strong>")) {
                Matcher matcher = pat.matcher(data);
                if (matcher.find()) {
                    handler.sendMessage(createMsg(matcher.group()));
                    return true;
                }
            }
        } catch (IOException e) {
            handler.sendMessage(createMsg("Error: "+e));
        }
        return false;
    }

    public static Message createMsg(String message) {
        Message msg = new Message();
        Bundle bnd = new Bundle();
        bnd.putString("msg", message);
        msg.setData(bnd);
        return msg;
    }

    protected void updateResult(String msg) {
        ((TextView) this.findViewById(R.id.resultfield)).setText(msg);
    }
}
